<template>
  <a-modal
    :centered="true"
    :confirmLoading="confirmLoading"
    :title="title"
    :visible="visible"
    :width="modalWidth()"
    @cancel="handleCancel"
    class="update-modal"
  >
    <template slot="footer">
      <a-button ghost style="float: left" type="primary" @click="connection">
        测试连接
      </a-button>
      <a-button key="back" @click="handleCancel">
        取消
      </a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">
        确定
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div style="margin-bottom: 16px;display: flex;justify-content: center">
        <a-radio-group>
          <a-radio>数据库</a-radio>
          <a-radio :disabled="true">网页</a-radio>
          <a-radio :disabled="true">文本</a-radio>
        </a-radio-group>
      </div>
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
          label="连接名称"
        >
          <a-input
            v-decorator="['connectName', {rules: [{required: true, message: '请输入连接名称！'}]}]"
            placeholder="请输入连接名称" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="数据库类型"
        >
          <a-select
            v-decorator="['datasourceType', {rules: [{ required: true, message: '请选择数据库类型！' }]}]"
            placeholder="请选择数据库类型"
            style="width: 100%">
            <a-select-option v-for="(item,index) in typeData" :key="index" :value="item.name">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="数据库名称:">
              <a-input
                v-decorator="['databaseName', {rules: [{required: true, message: '请输入数据库名称！'}]}]"
                placeholder="请输入数据库名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="数据库IP:">
              <a-input
                v-decorator="['ip', {rules: [{required: true, message: '请输入数据库IP！'}]}]"
                placeholder="请输入数据库IP"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="端口:">
              <a-input
                v-decorator="['port', {rules: [{required: true, message: '请输入正确的端口号！',pattern: /^[0-9]*$/ }, { validator: this.formatPort }]}]"
                placeholder="请输入端口"
              ></a-input>
            </a-form-item>
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="密码:">
              <a-input
                v-decorator="['password', {rules: [{required: true, message: '请输入密码！'}]}]"
                placeholder="请输入密码"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="用户名:">
              <a-input
                v-decorator="['username', {rules: [{required: true, message: '请输入用户名！'}]}]"
                placeholder="请输入用户名"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="centerLabelCol"
              :wrapperCol="centerWrapperCol"
              label="是否中央仓库:">
              <a-select
                v-decorator="['isWarehouse', {rules: [{ required: true, message: '' }]}]"
                style="width: 100%">
                <a-select-option v-for="(item,index) in [1,0]" :key="index" :value="item">{{ item === 1 ? '是' : '否' }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
          label="连接URL"
        >
          <a-input
            v-decorator="['url', {rules: [{required: true, message: '请输入连接URL!'}]}]"
            placeholder="请输入连接URL" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { datasourceAdd, datasourceEdit, testConnection } from '@/api/modular/main/knowl/data_source/dataSourceManager'
import { register } from '@/utils/drag_modal'

export default {
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      centerLabelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      centerWrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },

      typeData: [],
      sqlDriver: [],
      visible: false,
      title: '',
      id: undefined,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  methods: {
    modalWidth() {
      return document.body.clientWidth * 0.5
    },
    // 初始化方法
    add() {
      this.id = undefined
      this.title = '新增数据源'
      this.visible = true
      register(true)
      const parentIdOption = this.$options
      this.typeData = parentIdOption.filters['dictData']('sql_type')
      this.sqlDriver = parentIdOption.filters['dictData']('sql_driver')
      this.$nextTick(() => {
        this.form.setFieldsValue(
          {
            isWarehouse: 1
          }
        )
      })
    },
    // 编辑
    edit(item) {
      this.id = item.id
      this.title = '编辑数据源'
      this.visible = true
      register(true)
      const parentIdOption = this.$options
      this.typeData = parentIdOption.filters['dictData']('sql_type')
      this.sqlDriver = parentIdOption.filters['dictData']('sql_driver')
      this.$nextTick(() => {
        this.form.setFieldsValue(
          {
            connectName: item.connectName,
            databaseName: item.databaseName,
            ip: item.ip,
            datasourceType: item.datasourceType,
            password: item.password,
            username: item.username,
            port: item.port,
            isWarehouse: item.isWarehouse ? parseInt(item.isWarehouse) : 1,
            url: item.url
          }
        )
      })
    },
    formatPort(rule, value, callback) {
      callback()
    },
    addItem(values) {
      this.confirmLoading = true
      datasourceAdd(values).then((res) => {
        if (res.success) {
          this.$message.success('新增成功')
          this.confirmLoading = false
          this.$emit('ok', values)
          this.handleCancel()
        } else {
          this.$message.error('新增失败')
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    editItem(values) {
      values['id'] = this.id
      this.confirmLoading = true
      datasourceEdit(values).then((res) => {
        if (res.success) {
          this.$message.success('编辑成功')
          this.confirmLoading = false
          this.$emit('ok', values)
          this.handleCancel()
        } else {
          this.$message.error('编辑失败')
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof (values[key]) === 'object') {
              values[key] = JSON.stringify(values[key])
            }
          }
          const driver = this.sqlDriver.find((it) => it['code'] === values['datasourceType'])
          values['driver'] = driver['name']
          if (this.id) {
            this.editItem(values)
          } else {
            this.addItem(values)
          }
        }
      })
    },
    connection() {
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          for (const key in values) {
            if (typeof (values[key]) === 'object') {
              values[key] = JSON.stringify(values[key])
            }
          }
          this.confirmLoading = true
          testConnection(values)
            .then((res) => {
              if (res.data === 'success') {
                this.$message.info('连接成功!')
              } else {
                this.$message.error('连接失败!')
              }
            })
            .catch((_) => {
              this.$message.error('连接失败!')
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      register(false)
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
